package 深度优先搜索;

import java.util.LinkedList;

public class Solution210课程表2 {
    public int[] findOrder(int numCourses, int[][] prerequisites) {

        int[] indegree=new int[numCourses];
        for(int[] p:prerequisites){
            indegree[p[0]]++;
        }
        LinkedList<Integer> queue=new LinkedList<>();
        for(int i=0;i<numCourses;i++){
            if(indegree[i]==0){
                queue.addLast(i);
            }
        }
        int[] result=new int[numCourses];
        int index=0;
        while (!queue.isEmpty()){
            int value=queue.removeFirst();
            result[index]=value;
            index++;

            for(int[] p2:prerequisites){
                if(p2[1]!=value){
                    continue;
                }
                if(--indegree[p2[0]]==0){
                    queue.addLast(p2[0]);
                }
            }
        }
        if (index==numCourses){
            return result;
        }
        return new int[0];
    }
}
